package com.test.auth_db_auto.support;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


/**
 * @ Author: .Mr
 * @ ClassName AuthenticationProviderImpl
 * @ Description TODO
 * @ date 2021/12/31 11:28
 * @ Version 1.0
 * 自定义账号密码的加密方式并验证方式
 */
public class AuthenticationProviderImpl extends DaoAuthenticationProvider {

    private UserDetailsService userDetailsService;

    public AuthenticationProviderImpl(UserDetailsService userDetailsService){
        this.userDetailsService=userDetailsService;
    }
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username=authentication.getName();
        String password=authentication.getCredentials().toString();
        UserDetails account=userDetailsService.loadUserByUsername(username);

        if(!account.isAccountNonLocked()){
            throw new BadCredentialsException("帐号已锁定！");
        }
        if(!account.isAccountNonExpired()){
            throw new BadCredentialsException("帐号已过期！");
        }
        //检验密码是否正确
//        String encode = new BCryptPasswordEncoder().encode(password);
//        System.out.println("[    -------  "+new BCryptPasswordEncoder().matches(password,encode));
        //自定义加密方式
       /* if(!password.equals(account.getPassword())){
            throw new BadCredentialsException("密码错误！");
        }*/
        //BCrypt加密方式
        if(!new BCryptPasswordEncoder().matches(password,account.getPassword())){
            throw new BadCredentialsException("密码错误！");
        }

        return new UsernamePasswordAuthenticationToken(account,account.getPassword(),account.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return UsernamePasswordAuthenticationToken.class.equals(aClass);
    }

}
